package com.sample.android.main;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.sample.android.entity.Utilisateur;
import com.sample.android.wifi.R;

import android.app.Activity;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public class syncUserFragment extends Fragment
{

	/**
	 * Callback interface through which the fragment will report the task's
	 * progress and results back to the Activity.
	 */
	static interface TaskCallbacks
	{
		void onPreExecute();

		void onProgressUpdate(int percent);

		void onCancelled();

		void onPostExecute();

		void processFinish(int output, Utilisateur utilisateur);
	}

	private TaskCallbacks	mCallbacks;
	private DummyTask		mTask;
	private String			email;
	private String			mdp;

	/**
	 * Hold a reference to the parent Activity so we can report the task's
	 * current progress and results. The Android framework will pass us a
	 * reference to the newly created Activity after each configuration change.
	 */
	@Override
	public void onAttach(Activity activity)
	{
		super.onAttach(activity);
		mCallbacks = (TaskCallbacks) activity;
	}

	/**
	 * This method will only be called once when the retained Fragment is first
	 * created.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		// Retain this fragment across configuration changes.
		setRetainInstance(true);

		// here is your arguments
		Bundle bundle = getArguments();

		// here is your list array
		this.email = bundle.getString("email");
		this.mdp = bundle.getString("mdp");

		// Create and execute the background task.
		mTask = new DummyTask();
		mTask.execute();
	}

	/**
	 * Set the callback to null so we don't accidentally leak the Activity
	 * instance.
	 */
	@Override
	public void onDetach()
	{
		super.onDetach();
		mCallbacks = null;
	}

	/**
	 * A dummy task that performs some (dumb) background work and proxies
	 * progress updates and results back to the Activity.
	 * 
	 * Note that we need to check if the callbacks are null in each method in
	 * case they are invoked after the Activity's and Fragment's onDestroy()
	 * method have been called.
	 */
	private class DummyTask extends AsyncTask<Void, Integer, Void>
	{
		private int			nbrow	= 0;
		private Utilisateur	utilisateur;

		@Override
		protected void onPreExecute()
		{
			if (mCallbacks != null)
			{
				mCallbacks.onPreExecute();
			}
		}

		/**
		 * Note that we do NOT call the callback object's methods directly from
		 * the background thread, as this could result in a race condition.
		 */
		@Override
		protected Void doInBackground(Void... ignore)
		{
			String strURL = "http://192.168.1.158/sybe/syncUser.php";

			InputStream is = null;
			String result = "";
			String returnString = "";

			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("email", email));
			nameValuePairs.add(new BasicNameValuePair("mdp", mdp));
			try
			{
				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(strURL);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();

			}
			catch (Exception e)
			{
				Log.e("log_tag", "Error in http connection " + e.toString());
			}

			try
			{
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null)
				{
					sb.append(line + "\n");
				}
				is.close();
				result = sb.toString();
			}
			catch (Exception e)
			{
				Log.e("log_tag", "Error converting result " + e.toString());
				returnString = returnString + " [Error converting result] ";
			}

			try
			{
				JSONArray jArray = new JSONArray(result);
				for (int i = 0; i < jArray.length(); i++)
				{
					JSONObject json_data = jArray.getJSONObject(i);
					nbrow = json_data.getInt("nbrow");
					utilisateur = new Utilisateur();
					utilisateur.setEmail(json_data.getString("email"));
					utilisateur.setPassword(json_data.getString("pass"));
					utilisateur.setBirthday(json_data.getString("birthday"));
					utilisateur.setId(json_data.getInt("_id"));
				}
			}
			catch (JSONException e)
			{
				Log.e("log_tag", "Error parsing data " + e.toString());
				returnString = returnString + " [Error parsing data] ";
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... percent)
		{
			if (mCallbacks != null)
			{
				mCallbacks.onProgressUpdate(percent[0]);
			}
		}

		@Override
		protected void onCancelled()
		{
			if (mCallbacks != null)
			{
				mCallbacks.onCancelled();
			}
		}

		@Override
		protected void onPostExecute(Void ignore)
		{
			if (mCallbacks != null)
			{
				mCallbacks.onPostExecute();
				mCallbacks.processFinish(nbrow, utilisateur);
			}
		}
	}
}
